package com.lgj.gateway.config;

import com.lgj.gateway.route.GateWayDynamicRoute;
import com.lgj.gateway.jdbc.RouteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.InMemoryRouteDefinitionRepository;
import org.springframework.cloud.gateway.route.RedisRouteDefinitionRepository;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;

/**
 * @author: guangjie.liao
 * @Date: 2022/10/24 19:33
 * @Description:
 */
@Configuration
public class BeanAutoConfiguration {
    @Value("${spring.cloud.gateway.redis-route-definition-repository.enabled}")
    private Boolean isRedis ;

    @Resource
    private RouteRepository routeRepository;

    @Resource
    private ApplicationEventPublisher publisher;

    @Resource
    private RedisRouteDefinitionRepository redisRouteDefinitionRepository;


    @Bean
    public GateWayDynamicRoute gateWayDynamicRoute(){
        RouteDefinitionRepository repository = redisRouteDefinitionRepository;
        return new GateWayDynamicRoute(repository,publisher,routeRepository);
    }

    @Bean
    public ReactiveRedisTemplate<String, String> stringReactiveRedisTemplate(
            ReactiveRedisConnectionFactory reactiveRedisConnectionFactory,
            ResourceLoader resourceLoader) {
        RedisSerializer<String> serializer = new StringRedisSerializer();
        RedisSerializationContext<String , String> serializationContext = RedisSerializationContext
                .<String, String>newSerializationContext()
                .key(serializer)
                .value(serializer)
                .hashKey(serializer)
                .hashValue(serializer)
                .build();
        return new ReactiveRedisTemplate<>(reactiveRedisConnectionFactory,serializationContext);
    }
}
